﻿using Framework.AssetsManager;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SkinnedMeshCombiner : MonoBehaviour
{
    public GameObject skeleton;

    void CombineObject(GameObject meshes, bool isMainCharacter)
    {
        meshes.transform.parent = skeleton.transform; 
        // Fetch all bones of the skeleton
        List<Transform> transforms = new List<Transform>();
        transforms.AddRange(skeleton.GetComponentsInChildren<Transform>(true));

        List<Transform> bones = new List<Transform>();//the list of bones

        // Collect information from meshes
        SkinnedMeshRenderer smr = meshes.GetComponentInChildren<SkinnedMeshRenderer>();
        smr.shadowCastingMode = isMainCharacter ? UnityEngine.Rendering.ShadowCastingMode.On : UnityEngine.Rendering.ShadowCastingMode.Off;
        smr.receiveShadows = isMainCharacter;
        foreach (var amaterial in smr.materials)
            amaterial.shader = Shader.Find(isMainCharacter ? "Mobile/Diffuse" : "Unlit/Texture");
        // Collect bones
        for (int j = 0; j < smr.bones.Length; j++)
        {
            int tBase = 0;
            for (tBase = 0; tBase < transforms.Count; tBase++)
            {
                if (smr.bones[j].name.Equals(transforms[tBase].name))
                {
                    bones.Add(transforms[tBase]);
                    break;
                }
            }
        }

        meshes.transform.parent = skeleton.transform;
        meshes.transform.localPosition = Vector3.zero;
        Material[] materials = smr.materials;

        smr.bones = bones.ToArray();
        bones.Clear();
    }
}
